package com.swz.dcrm.ui.boutique;


import android.animation.ValueAnimator;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.swz.dcrm.adpter.BoutiqueAdapter;
import com.swz.dcrm.adpter.BoutiqueDetailAdapter;
import com.swz.dcrm.adpter.BoutiqueGroupAdapter;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.base.ViewHolder;
import com.swz.dcrm.model.Boutique;
import com.swz.dcrm.model.BoutiqueGroup;
import com.swz.dcrm.model.Input;
import com.swz.dcrm.model.PageResponse;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.CarManagementViewModel;
import com.swz.dcrm.ui.viewmodel.MainViewModel;
import com.swz.dcrm.util.CustomDecoration;
import com.swz.dcrm.util.HorizontalDecoration;
import com.swz.dcrm.util.Tool;


import com.swz.dcrm.widget.TriangleView;
import com.xh.baselibrary.callback.OnClickListener;
import com.xh.baselibrary.util.AnimationUtil;
import com.xh.baselibrary.widget.BounceScrollView;


import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class BoutiqueFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.rv_boutique_group)
    RecyclerView rvBoutiqueGroup;
    private BoutiqueGroupAdapter boutiqueGroupAdapter;
    @BindView(R.id.rv_boutique)
    RecyclerView rvBoutique;
    @BindView(R.id.tv_total)
    TextView total;
    @BindView(R.id.c_detail)
    ConstraintLayout cDetail;
    @BindView(R.id.rv_detail)
    RecyclerView rvDetail;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.et_search)
    TextView etSearch;
    private int tvSearchWidth;

    private BoutiqueDetailAdapter detailAdapter;


    private BoutiqueAdapter boutiqueAdapter;
    @Inject
    MainViewModel mainViewModel;


    @Inject
    CarManagementViewModel carManagementViewModel;

    public static BoutiqueFragment newInstance() {

        return new BoutiqueFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())) {
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }

        //TODO 获取套餐
        carManagementViewModel.getBoutiqueGroup().observe(this, boutiqueGroupPageResponse -> {

            if (boutiqueGroupPageResponse.isSuccess()) {
                if (boutiqueGroupAdapter == null) {
                    boutiqueGroupAdapter = new BoutiqueGroupAdapter(getContext(), boutiqueGroupPageResponse.getData());
                    boutiqueGroupAdapter.setOnClickListener(groupOnClickListener);
                    rvBoutiqueGroup.setAdapter(boutiqueGroupAdapter);
                    getBoutiques(boutiqueGroupPageResponse.getData().get(0).getBoutiqueIds());

                }
            }
        });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_boutique;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);

        mainViewModel.getInput().setValue(new Input(rvDetail, 0, false));
        rvDetail.setLayoutManager(new LinearLayoutManager(getContext()));
        title.setText(getString(R.string.boutique_title));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        rvBoutiqueGroup.setLayoutManager(linearLayoutManager);
        rvBoutiqueGroup.addItemDecoration(new HorizontalDecoration(getContext(), 0, 15));
        rvBoutique.setLayoutManager(new LinearLayoutManager(getContext()));
        if (carManagementViewModel.getSelectedBoutique().getValue() != null) {
            detailAdapter = new BoutiqueDetailAdapter(getContext(), carManagementViewModel.getSelectedBoutique().getValue());
            total.setText(getString(R.string.boutique_fee_in_total, detailAdapter.getDatas().size(), detailAdapter.getTotal()));
        } else {
            detailAdapter = new BoutiqueDetailAdapter(getContext(), new ArrayList<>());
            total.setText(getString(R.string.boutique_fee_in_total, 0, "¥0"));
        }
        detailAdapter.setOnClickListener(onClickListener);
        rvDetail.setAdapter(detailAdapter);

        //todo 套餐返回监听
        carManagementViewModel.getBoutiques().observe(this, boutiquePageResponse -> {
            if (boutiquePageResponse != null && boutiquePageResponse.isSuccess()) {
                List<Boutique> list = new ArrayList<>();
                list.addAll(boutiquePageResponse.getData());
                Boutique boutique = new Boutique();
                boutique.setBoutiqueName("全部");
                list.add(boutique);
                boutiqueAdapter = new BoutiqueAdapter(getContext(), list);
                boutiqueAdapter.setOnClickListener(boutiqueOnClickListener);
                rvBoutique.setAdapter(boutiqueAdapter);

            }
        });
        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String searchTag = etSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(searchTag)) {
                    mainViewModel.getInput().setValue(new Input(etSearch,0,false));
                    carManagementViewModel.getBoutiques(null, searchTag);
                }
                return true;
            }
            return false;
        });
        return true;
    }

    OnClickListener<BoutiqueGroup> groupOnClickListener = boutiqueGroup -> {
        boutiqueGroupAdapter.smoothMoveToPosition(rvBoutiqueGroup, boutiqueGroupAdapter.getCurrentClickPosition());
        getBoutiques(boutiqueGroup.getBoutiqueIds());
    };

    @OnClick({R.id.tv_detail})
    public void detail() {
        if (rvDetail.getVisibility() == View.GONE) {
            if (detailAdapter == null || detailAdapter.getItemCount() == 0) {
                return;
            }
            ll.setAlpha(0.6f);
            rvDetail.setVisibility(View.VISIBLE);
            rvDetail.setAnimation(AnimationUtil.moveToViewLocation());
        } else {
            ll.setAlpha(1);
            rvDetail.setVisibility(View.GONE);
            rvDetail.setAnimation(AnimationUtil.moveToViewBottom());
        }
    }

    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }

    @OnClick(R.id.tv_search)
    public void tvSearch() {
        tvSearchWidth = tvSearch.getWidth();
        tvSearch.setVisibility(View.GONE);
        etSearch.requestFocus();
        rvBoutiqueGroup.setVisibility(View.GONE);
        mainViewModel.getInput().setValue(new Input(etSearch, 0, true));
        ValueAnimator valueAnimator1 = ValueAnimator.ofInt(0, Tool.dip2px(getActivity(), 72));
        valueAnimator1.addUpdateListener(animation -> {

            ViewGroup.LayoutParams layoutParams = etSearch.getLayoutParams();
            layoutParams.width = tvSearchWidth - (int) animation.getAnimatedValue();
            etSearch.setLayoutParams(layoutParams);
        });
        valueAnimator1.setDuration(300);
        valueAnimator1.start();
    }

    @OnClick(R.id.tv_cancel)
    public void cancel() {
        ValueAnimator valueAnimator1 = ValueAnimator.ofInt(0, Tool.dip2px(getActivity(), 72));
        valueAnimator1.addUpdateListener(animation -> {

            ViewGroup.LayoutParams layoutParams = etSearch.getLayoutParams();
            layoutParams.width = tvSearchWidth - Tool.dip2px(getActivity(), 72) + (int) animation.getAnimatedValue();
            etSearch.setLayoutParams(layoutParams);
            if ((int) animation.getAnimatedValue() == Tool.dip2px(getActivity(), 72)) {
                tvSearch.setVisibility(View.VISIBLE);
                rvBoutiqueGroup.setVisibility(View.VISIBLE);
                mainViewModel.getInput().setValue(new Input(etSearch, 0, false));
                if (boutiqueGroupAdapter != null) {
                    getBoutiques(boutiqueGroupAdapter.getDatas().get(boutiqueGroupAdapter.getCurrentClickPosition()).getBoutiqueIds());
                }
            }
        });
        valueAnimator1.setDuration(300);
        valueAnimator1.start();
    }

    @OnClick(R.id.btn_make_sure)
    public void sure() {
        carManagementViewModel.getSelectedBoutique().setValue(detailAdapter.getDatas());
        backClick();
    }

    public void getBoutiques(String ids) {
        carManagementViewModel.getBoutiques(ids, null);
    }

    OnClickListener<Boutique> onClickListener = new OnClickListener<Boutique>() {
        @Override
        public void onItemClick(Boutique boutique) {
            if (detailAdapter.getItemCount() == 0) {
                ll.setAlpha(1);
                rvDetail.setVisibility(View.GONE);
                rvDetail.setAnimation(AnimationUtil.moveToViewBottom());
            }
            total.setText(getString(R.string.boutique_fee_in_total, detailAdapter.getDatas().size(), detailAdapter.getTotal()));
        }
    };
    OnClickListener<Boutique> boutiqueOnClickListener = new OnClickListener<Boutique>() {
        @Override
        public void onItemClick(Boutique boutique) {

            if (boutique.getId() != 0) {
                if (!detailAdapter.getDatas().contains(boutique)) {
                    detailAdapter.addItem(boutique);

                    total.setText(getString(R.string.boutique_fee_in_total, detailAdapter.getDatas().size(), detailAdapter.getTotal()));
                } else {
                    showToast("该精品以添加");
                }
            } else {
                if (boutiqueAdapter.getSelected() != null && boutiqueAdapter.getSelected().size() > 0) {
                    for (Boutique boutique1 : boutiqueAdapter.getSelected()) {
                        if (!detailAdapter.getDatas().contains(boutique1)) {
                            detailAdapter.addItem(boutique1);
                        }
                    }
                }
                total.setText(getString(R.string.boutique_fee_in_total, detailAdapter.getDatas().size(), detailAdapter.getTotal()));
            }

        }
    };
}
